package cn.newtouch.system.controller;

import cn.newtouch.basic.annotation.PreAuthorize;
import cn.newtouch.basic.util.JsonResult;
import cn.newtouch.basic.util.PageList;
import cn.newtouch.system.domain.Menu;
import cn.newtouch.system.query.MenuQuery;
import cn.newtouch.system.service.IMenuService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 接口类：菜单
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    public IMenuService menuService;

    /**
     * 添加或修改
     * @param menu  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    @PreAuthorize(name = "保存菜单",sn = "menu:save")
    public JsonResult addOrUpdate(@RequestBody Menu menu){
        try {
            if( menu.getId()!=null)
                menuService.update(menu);
            else
                menuService.save(menu);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败！！");
        }
    }

    /**
    * 删除
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    @PreAuthorize(name = "删除菜单",sn = "menu:delete")
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            menuService.remove(id);
            return JsonResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return JsonResult.me().setMsg("删除失败！！");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除")
    @PreAuthorize(name = "批量删除菜单",sn = "menu:patchDel")
    public JsonResult patchDelete(@RequestBody List<Long> ids){
        try {
            menuService.patchDel(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("批量删除失败！！");
        }
    }


    /**
    * 查询单个信息
    * @param id
    */
    @GetMapping("/{id}")
    @PreAuthorize(name = "根据id查询菜单",sn = "menu:get")
    public Menu findOne(@PathVariable("id")Long id) {
        return menuService.loadById(id);
    }


    /**
    * 查询所有信息
    * @return
    */
    @GetMapping
    @PreAuthorize(name = "所有菜单",sn = "menu:getAll")
    public List<Menu> findAll(){
        return menuService.loadAll();
    }


   /**
    * 分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    @PreAuthorize(name = "分页查询菜单",sn = "menu:list")
    public PageList<Menu> queryPage(@RequestBody MenuQuery query) {

        return menuService.queryPage(query);
    }


    /**
     * 查询菜单树
     * @return
     */
    @GetMapping("/menuTree")
    @ApiOperation(value = "获取菜单树-无限极接口")
    @PreAuthorize(name = "菜单树",sn = "menu:tree")
    public List<Menu> menuTree(){
        return menuService.menuTree();
    }
}